package shared;

import java.awt.Point;

import main.Map;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Polygon;

import entities.Player;

public class Grid {
	private static int size;
	private static int mouseX;
	private static int mouseY;
	private static boolean shouldDraw;
	
	public static void init(int size) {
		Grid.size = size;
		shouldDraw = false;
	}
	
	public static void setSize(int size) {
		Grid.size = size;
	}
	
	public static int getSize() {
		return size;
	}
	
	public static Point calculateGridPosition(int x, int y) {
		int newX = (x / size) * size;
		int newY = (y / size) * size;
		
		if(x < 0 && (x % size) != 0)
			newX -= 50;
		
		if(y < 0 && (y % size) != 0)
			newY -= 50;
		
		return new Point(newX, newY);
	}
	
	public static void update(GameContainer gc, Player player) {
		int midX = player.getX() + player.getWidth()/2;
		int midY = player.getY() + player.getHeight()/2;
		mouseX = MouseInput.getMousePosX();
		mouseY = MouseInput.getMousePosY();
		
		Point topLeft = Grid.calculateGridPosition(midX, midY);
		topLeft.setLocation(topLeft.getX()-Grid.getSize(), topLeft.getY()-2*Grid.getSize());
		int width = 3 * Grid.getSize();
		int height = 4 * Grid.getSize();
		
		Polygon poly = new Polygon(new float[] {(float) topLeft.getX(), (float) topLeft.getY(),
												(float) (topLeft.getX() + width), (float) topLeft.getY(),
												(float) (topLeft.getX() + width), (float) (topLeft.getY() + height),
												(float) topLeft.getX(), (float) (topLeft.getY() + height)});
		
		/* Field the player place blocks/
		 * xxx 1
		 * xxx 2
		 * xpx 3
		 * xxx 4
		 */
		if(poly.contains(mouseX, mouseY) && (player.getActiveItem().getType().equals("tool") || player.getActiveItem().getType().equals("block"))) {
			Point playerPos = Grid.calculateGridPosition(midX, midY);
			Point mousePos = Grid.calculateGridPosition(mouseX, mouseY);
			if(playerPos.getX() != mousePos.getX() || playerPos.getY() != mousePos.getY()) {
				shouldDraw = true;
			} else {
				shouldDraw = false;
			}
		} else {
			shouldDraw = false;
		}
		
		Point p = calculateGridPosition(mouseX, mouseY);
		mouseX = (int) p.getX();
		mouseY = (int) p.getY();
	}
	
	public static void drawMousePositionOnGrid(Graphics g) {
		if(shouldDraw) {
			g.setColor(Color.white);
			g.drawRect(mouseX, mouseY, size, size);
		}
	}
}
